
// 相当于mvc项目中的controller
let connection = require('../db.js')
// 查询用户列表
exports.users = function(req,res){
  connection.query('select * from user',(err,users)=>{
    if(err){
      res.send('query error')
    }else{
      res.render('users',{title:'用户列表',data: users,text:'00'})
    }
  })
 
}

// 用户编辑回显
exports.editUsers = function(req,res){
  let id = req.params.id
  connection.query(`select * from user where id = ${id}`,(err,data)=>{
    if(err){
      res.send('query error')
    }else{
      console.log(data)
      res.render('form',{title:'编辑列表',data: data[0],text:'00'})
    }
  })
}

// 用户编辑保存,新增保存
exports.updateAdd = function(req,res){
  console.log(req.body)
  // 如果存在id就进行编辑，如果不存在就进行新增
  let sql = ''
  if(req.body.id){
    sql = `update user set name="${req.body.name}", age=${req.body.age}, password="${req.body.password}" where id=${req.body.id}`
  }else{
    sql = `insert into user (name,1age,password) values("${req.body.name}",${req.body.age}, "${req.body.password}")`
  }
  connection.query(sql,(err,user)=>{
    if(err){
      res.send('query error',err)
    }else{
      res.redirect('/');
    }
  })
}

// 删除用户列表
exports.deleteUsers = function(req,res){
  let id = req.params.id
  connection.query(`delete from user where id =${id}`,(err,users)=>{
    if(err){
      res.send('query error')
    }else{
      res.redirect('/');
    }
  })
}
// 新增页面返回
exports.cancel = function(req,res){
  res.redirect('/');
}

// 新增用户页面的跳转
exports.userAddPage = function(req,res){
  let user = {}
  res.render('form',{title: '用户新增',data: {}});
}

// 上传文件的跳转
exports.upload = function(req,res){
  res.render('upload')
}

let fs = require('fs')
// 上传文件
exports.uploadFile = function(req,res){
  console.log(req.file);  // 上传的文件信息
  // var des_file = "./upload/" + req.file.originalname;
  // fs.readFile( req.file.path, function (err, data) {
  //     fs.writeFile(des_file, data, function (err) {
  //         if( err ){
  //             console.log( err );
  //         }else{
  //             response = {
  //                 message:'File uploaded successfully',
  //                 filename:req.file.originalname
  //             };
  //             // console.log( response );
  //             // res.end( JSON.stringify( response ) );
  //         }
  //     });
  // });
}

